<?php defined('SYSPATH') or die('No direct script access.');

class Model_Note extends ORM
{  
    protected $_table_name = 'notes';
    protected $_reload_on_wakeup = false;
    
    public function get_notes(Model_Ticket $ticket)
    {
        return $this->_get_notes_query()
                    ->where('ticket_id', '=', $ticket->id)
                    ->order_by('updated', 'DESC')
                    ->find_all()
                    ->as_array();        
    }
    
    public function getAttachments()
    {
        $attachments = json_decode($this->attachments, true);
        $ticket = ORM::factory('ticket', $this->ticket_id);
        foreach ($attachments as &$attachment) {
            //$tmp = explode("\\", $attachment['filePath']); 
            //if (count($tmp) < 2) {
                $tmp = explode("/", $attachment['filePath']);   
            //}
            $filename = $tmp[count($tmp)-1];
            $filename = '/media/uploads/attachments/'.$ticket->mailbox_id.'/'.$filename;
            $attachment['filename'] = $filename;
            $attachment['filesize'] = Model_Main::filesize_format(filesize($attachment['filePath'])); 
        }
        return $attachments;         
    }
    
    protected function _get_notes_query()
    {
        return ORM::factory('note');
    }
    
    public function add_note(Model_Ticket $ticket, $text, $attachments = array())
    {
        $user_id = 0;
        $user = Model_Auth::instance()->get_user();
        if ($user) {
            $user_id = $user->id;   
        }
        
        $mailbox = ORM::factory('mailbox', $ticket->mailbox_id);
        $company = Model_Main::get_company();
        if ($company->id != $mailbox->company_id) {
            throw new HTTP_Exception_404('Такой компании нет');    
        }
        
        $text       = Security::xss_clean($text);
        
        $this->ticket_id    = $ticket->id;
        $this->user_id      = $user_id;
        $this->text         = $text;
        $this->created      = $this->updated = time(); 
        if (count($attachments)) {
            $this->attachments = json_encode($attachments);   
        }       
        $this->save();
        
        $ticket->update_ticket_updated_time();
        
        return $this;  
    }
}
